# function: search log

import os
import sys
import queue
import re

class FileOption:
    def getAllFiles(self,filePath,suffix,queue):
        print("getAllFiles------>filePath:",filePath)
        isDirExist = os.path.exists(filePath.strip())
        print(isDirExist)
        if not isDirExist:
            print("the file path: %s  is not existing!"%filePath);
            return
        fileNames = os.listdir(filePath.strip())
        absoluteFilePaths = [os.path.join(filePath,file) for file in fileNames]
        print("the file absolute path :%s"%absoluteFilePaths)
        for absoluteFilePath in absoluteFilePaths:
            path,ext = os.path.splitext(absoluteFilePath)
            if suffix == ext:
                queue.put(absoluteFilePath)
    def wirteIntoFile(self,fileName,content):
        savefileName = "./"+fileName+".log"
        file = open(savefileName,"a+") # append mode
        file.write(content)
        file.close() # don't forget close the file
    def readFileLine(self,absoluteFilePath,searchStr):
        lines=""
        file = open(absoluteFilePath.strip(),"r")
        while True:
            line = file.readline()
            print("-------------:%s"%line)
            if not line:
                break
            match = re.search(searchStr,line)
            if match is  not None:
                lines=lines+'\n'+line
        file.close()
        return lines

if __name__ == '__main__':
    global queue 
    searchPath = input("input the path to search log:   ")
    key = input("input the searching key word:   ")
    suffix = input("input the log file's suffix, for example .log  .txt :    ") 
    outputFileName = input("input the output file name:   ")
    queue = queue.Queue()
    fileOption = FileOption()
    fileOption.getAllFiles(searchPath,suffix,queue)
    print(queue.qsize())
    print(queue.empty())
    while not queue.empty():
        lines = fileOption.readFileLine(queue.get(),key)
        print(lines)
        fileOption.wirteIntoFile(outputFileName,lines)









